setwd("")
rm(list=ls())
library(ggplot2)
library(dplyr)

data <- read.csv("../immigration_cace_results.csv", stringsAsFactors = FALSE)
var.names <- read.csv("../imm_var_names.csv", stringsAsFactors = FALSE)

make.cace <- function(dv) {
  # Pick which variable to plot
  data <- subset(data, data$DV == dv)
  title <- var.names[var.names$dv == dv, "caption"]
  
  # Get overall results
  all.respondents.eddie <- data[data$Exposures == "All respondents" & data$Treat == "treat_eddie", 
                                "Estimate"]
  all.respondents.maricruz <- data[data$Exposures == "All respondents" & data$Treat == "treat_maricruz", 
                                "Estimate"]
  any.compliers.eddie <- data[data$Exposures == "Any compliers" & data$Treat == "treat_eddie",
                              "Estimate"]
  any.compliers.maricruz <- data[data$Exposures == "Any compliers" & data$Treat == "treat_maricruz",
                              "Estimate"]
  data <- subset(data, !(data$Exposures %in% c("All respondents", "Any compliers")))
  data$Exposures <- as.numeric(data$Exposures)
  
  all.respondents <- data.frame(rbind(all.respondents.eddie, all.respondents.maricruz))
  all.respondents$Treat <- c("Eddie + Prosperous Future", "MariCruz/Kandy + Prosperous Future")
  names(all.respondents)[1] <- "effect"
  
  any.compliers <- data.frame(rbind(any.compliers.eddie, any.compliers.maricruz))
  any.compliers$Treat <- c("Eddie + Prosperous Future", "MariCruz/Kandy + Prosperous Future")
  names(any.compliers)[1] <- "effect"
  
  data <- data %>%
    mutate(Treat = recode(Treat, "treat_eddie" = "Eddie + Prosperous Future", "treat_maricruz" = "MariCruz/Kandy + Prosperous Future"))

  plot <- ggplot(data, aes(x = Exposures, y = Estimate, size = 1/SE^2)) + 
    geom_point(shape = 21) +
    geom_smooth(method = "lm", mapping = aes(weight = 1/SE^2), 
                color = "black") +
    geom_hline(data = all.respondents, aes(yintercept = effect, linetype="All respondents"), color = "red") +
    geom_hline(data = any.compliers, aes(yintercept = effect, linetype="Saw ad at least once"), color = "blue") +
    scale_linetype_manual(name = NULL, values = c("dashed", "solid"), 
                          guide = guide_legend(override.aes = list(color = c("red", "blue")))) +
    labs(title = paste0("Effect on ", title), caption = "Note: Fitted line weighted by the precision of each observation.") + 
    theme_bw() +
    theme(legend.position = "bottom") +
    scale_size(guide=FALSE) +
    facet_wrap(~ Treat)
  ggsave(paste(dv, ".pdf"), plot)
}

for (i in 1:nrow(var.names)) {
  make.cace(var.names[i, "dv"])
}